<template>
  <div class="app-container">
    <div class="txz-editor">
      <!-- 顶部工具栏 -->
      <div class="editor-toolbar">
        <div class="toolbar-left">
          <el-button @click="handlePrevious">
            <el-icon><Back /></el-icon>返回
          </el-button>

          <el-divider direction="vertical" />

          <el-button @click="handlePreview">
            <el-icon><View /></el-icon>预览
          </el-button>

          <el-button @click="handleSave">
            <el-icon><Document /></el-icon>保存
          </el-button>

          <el-button @click="handleClear">
            <el-icon><Delete /></el-icon>清空
          </el-button>

          <el-divider direction="vertical" />

          <el-button @click="handleImport">
            <el-icon><Upload /></el-icon>导入
          </el-button>

          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>导出
          </el-button>
        </div>

        <div class="toolbar-right">
          <!-- 页面切换按钮 -->
          <el-radio-group v-model="currentPageType" @change="handlePageTypeChange" size="default">
            <el-radio-button label="home">首页设计</el-radio-button>
            <el-radio-button label="user">用户中心设计</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 编辑区域 -->
      <div class="editor-content">
        <!-- 左侧组件列表 -->
        <div class="component-list">
          <div class="component-category" v-for="(components, category) in categorizedComponents" :key="category">
            <div class="category-divider">
              <span>{{ getCategoryName(category) }}</span>
            </div>
            <div class="component-grid">
              <div
                v-for="component in components"
                :key="component.type"
                class="component-item"
                @click="handleAddComponent(component.type, component.name)"
              >
                <div class="component-icon">
                  <el-icon :size="18">
                    <component :is="getIconComponent(component.icon)" />
                  </el-icon>
                </div>
                <div class="component-name">{{ component.name }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 中间预览区 -->
        <div class="preview-area" ref="previewAreaRef">
          <div class="preview-container" ref="previewContainerRef">
            <!-- 同步滚动容器 -->
            <div class="sync-scroll-container" ref="syncScrollRef">
              <div class="phone-and-labels">
                <!-- 手机模拟器 -->
                <div class="phone-container" :class="currentPageType === 'home' ? 'home-design' : 'user-design'" ref="phoneContainerRef">
                  <div class="phone-header">
                    <div class="phone-notch"></div>
                  </div>
                  <div class="phone-screen">
                    <div
                      class="page-content"
                      :style="{
                        backgroundColor: activeEditor?.state?.pageConfig?.backgroundColor || '#ffffff',
                        backgroundImage: activeEditor?.state?.pageConfig?.backgroundImage ? `url(${activeEditor.state.pageConfig.backgroundImage})` : 'none'
                      }"
                      ref="pageContentRef"
                      @wheel.passive="handleWheel"
                    >
                      <!-- 渲染非TabBar组件 -->
                      <div
                        v-for="(component, index) in nonTabBarComponents"
                        :key="component.id"
                        class="component-wrapper"
                        :class="{
                          'component-selected': activeEditor?.state?.selectedComponentIndex === getOriginalIndex(index)
                        }"
                        @click="handleSelectComponent(getOriginalIndex(index))"
                        :ref="(el) => componentRefs[getOriginalIndex(index)] = el"
                      >
                        <component
                          v-if="getComponentType(component.type)"
                          :is="getComponentType(component.type)"
                          :data="component.data"
                          :styles="component.styles"
                        />
                      </div>
                    </div>

                    <!-- TabBar固定在底部 -->
                    <div
                      v-for="(component, index) in tabBarComponents"
                      :key="component.id"
                      class="tabbar-container"
                      :class="{
                        'component-selected': activeEditor?.state?.selectedComponentIndex === getTabBarOriginalIndex(index)
                      }"
                      @click="handleSelectComponent(getTabBarOriginalIndex(index))"
                      :ref="(el) => componentRefs[getTabBarOriginalIndex(index)] = el"
                    >
                      <component
                        v-if="getComponentType(component.type)"
                        :is="getComponentType(component.type)"
                        :data="component.data"
                        :styles="component.styles"
                        :page-config="activeEditor?.state?.pageConfig || {}"
                      />
                    </div>
                  </div>
                  <div class="phone-footer"></div>
                </div>
              </div>
            </div>
          </div>

          <!-- 组件标签 -->
          <div class="component-labels">
            <!-- 1. 临时占位标签：组件渲染前先显示 -->
            <div
              v-if="isTempLabelShow"
              class="deles"
              :style="tempLabelStyle"
              @click.stop="handleDeleteComponent(tempLabelTargetIndex)"
            >
              <span class="triangle-left"></span>
              <span class="label-text">{{ tempLabelComponentName || '组件' }}</span>
              <i class="el-icon-delete-solid delete-icon" />
            </div>

            <!-- 2. 正式标签：显示所有组件的标签 -->
            <div
              v-for="(component, index) in activeEditor?.state?.components"
              :key="component.id"
              v-if="activeEditor?.state?.components.length > 0 && !isTempLabelShow"
              class="deles"
              :style="componentLabelPositions[index] || {}"
              ref="componentLabels"
            >
              <span class="triangle-left"></span>
              <span class="label-text">{{ component.name || COMPONENT_META[component.type]?.name || '组件' }}</span>

              <!-- 向上移动按钮 -->
              <div
                class="move-up-btn"
                v-if="index > 0"
                @click.stop="handleMoveUpLayer(index)"
                title="向上移动"
              >
                <i class="el-icon-caret-top"></i>
              </div>

              <!-- 向下移动按钮 -->
              <div
                class="move-down-btn"
                v-if="index < (activeEditor?.state?.components.length - 1 || 0)"
                @click.stop="handleMoveDownLayer(index)"
                title="向下移动"
              >
                <i class="el-icon-caret-bottom"></i>
              </div>

              <!-- 删除按钮 -->
              <i class="el-icon-delete-solid delete-icon" @click.stop="handleDeleteComponent(index)" />
            </div>
          </div>

          <!-- 3. 选中组件时显示的删除按钮 -->
          <div
            v-if="activeEditor?.state?.selectedComponentIndex !== null && activeEditor?.state?.components.length > 0"
            class="selected-delete-btn"
            :style="selectedDeleteBtnPosition"
            @click.stop="handleDeleteComponent(activeEditor?.state?.selectedComponentIndex || -1)"
            title="删除选中组件"
          >
            <i class="el-icon-remove"></i>
          </div>
        </div>

        <!-- 右侧属性面板 -->
        <div class="property-panel">
          <el-tabs v-model="activePropertyTab">
            <el-tab-pane label="页面设置" name="page">
              <PageConfigPanel
                :page-config="activeEditor?.state?.pageConfig || {}"
                @update="handleUpdatePageConfig"
              />
            </el-tab-pane>

            <el-tab-pane label="组件属性" name="component">
              <div v-if="activeEditor?.state?.selectedComponentIndex >= 0 && activeEditor?.state?.selectedComponent">
                <div class="component-info">
                  <h3>{{ activeEditor.state.selectedComponent.name || '未命名组件' }}</h3>
                </div>
                <div v-if="!getPropertyPanelType(activeEditor.state.selectedComponent.type)" class="no-property-panel">
                  <el-empty description="该组件暂无可配置属性" />
                </div>
                <div v-else>
                  <component
                    :is="getPropertyPanelType(activeEditor.state.selectedComponent.type)"
                    :data="activeEditor.state.selectedComponent.data"
                    :styles="activeEditor.state.selectedComponent.styles"
                    @update-data="handleUpdateComponentData"
                    @update-styles="handleUpdateComponentStyles"
                  />
                </div>
              </div>
              <div v-else class="no-property-panel">
                <el-empty description="请选择一个组件" />
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 预览对话框 -->
      <el-dialog
        v-model="previewVisible"
        title="页面预览"
        width="80%"
        top="5vh"
        destroy-on-close
      >
        <div class="preview-container">
          <div class="phone-container" :class="currentPageType === 'home' ? 'home-design' : 'user-design'">
            <div class="phone-header">
              <div class="phone-notch"></div>
            </div>
            <div class="phone-screen">
              <div
                class="page-content"
                :style="{
                  backgroundColor: activeEditor?.state?.pageConfig?.backgroundColor || '#ffffff',
                  backgroundImage: activeEditor?.state?.pageConfig?.backgroundImage ? `url(${activeEditor.state.pageConfig.backgroundImage})` : 'none'
                }"
              >
                <component
                  v-for="(component, index) in nonTabBarComponents"
                  :key="component.id"
                  :is="getComponentType(component.type)"
                  :data="component.data"
                  :styles="component.styles"
                />
              </div>

              <!-- TabBar固定在底部 -->
              <div
                v-for="(component, index) in tabBarComponents"
                :key="component.id"
                class="tabbar-container"
              >
                <component
                  v-if="getComponentType(component.type)"
                  :is="getComponentType(component.type)"
                  :data="component.data"
                  :styles="component.styles"
                  :page-config="activeEditor?.state?.pageConfig || {}"
                />
              </div>
            </div>
            <div class="phone-footer"></div>
          </div>
        </div>
      </el-dialog>

      <!-- 导入对话框 -->
      <el-dialog
        v-model="importVisible"
        title="导入页面"
        width="50%"
        destroy-on-close
      >
        <el-form>
          <el-form-item label="选择文件">
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :on-change="handleFileChange"
              :limit="1"
              accept=".json"
            >
              <el-button type="primary">选择文件</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="importVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmImport">确认导入</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { useDesignTempLogic } from './design_logic.js'
import { COMPONENT_META } from '@/components/diy/shared/constants.js'
// 导入属性面板组件
import PageConfigPanel from '@/components/diy/vue3/properties/PageConfigPanel.vue'
import SearchBlockPanel from '@/components/diy/vue3/properties/SearchBlockPanel.vue'
import ImageBannerPanel from '@/components/diy/vue3/properties/ImageBannerPanel.vue'
import TitleTextPanel from '@/components/diy/vue3/properties/TitleTextPanel.vue'
import GoodsCardPanel from '@/components/diy/vue3/properties/GoodsCardPanel.vue'
import GoodsListPanel from '@/components/diy/vue3/properties/GoodsListPanel.vue'
import MenuGridPanel from '@/components/diy/vue3/properties/MenuGridPanel.vue'
import MenuListPanel from '@/components/diy/vue3/properties/MenuListPanel.vue'
import CouponCardPanel from '@/components/diy/vue3/properties/CouponCardPanel.vue'
import SeckillBlockPanel from '@/components/diy/vue3/properties/SeckillBlockPanel.vue'
import GrouponBlockPanel from '@/components/diy/vue3/properties/GrouponBlockPanel.vue'
import UserCardPanel from '@/components/diy/vue3/properties/UserCardPanel.vue'
import UserWalletPanel from '@/components/diy/vue3/properties/UserWalletPanel.vue'
import UserCouponPanel from '@/components/diy/vue3/properties/UserCouponPanel.vue'
import NoticePanel from '@/components/diy/vue3/properties/NoticePanel.vue'
import RichTextPanel from '@/components/diy/vue3/properties/RichTextPanel.vue'
import VideoPanel from '@/components/diy/vue3/properties/VideoPanel.vue'
import GraphicNavigationPanel from '@/components/diy/vue3/properties/GraphicNavigationPanel.vue'
import TabBarPanel from '@/components/diy/vue3/properties/TabBarPanel.vue'
import MagicCubePanel from '@/components/diy/vue3/properties/MagicCubePanel.vue'
import AuxiliarySegmentationPanel from '@/components/diy/vue3/properties/AuxiliarySegmentationPanel.vue'
import StoreInformationPanel from '@/components/diy/vue3/properties/StoreInformationPanel.vue'
import FollowPanel from '@/components/diy/vue3/properties/FollowPanel.vue'
import SuspensionPanel from '@/components/diy/vue3/properties/SuspensionPanel.vue'
import OnlineServicePanel from '@/components/diy/vue3/properties/OnlineServicePanel.vue'

// 引入逻辑模块并解构所有变量和方法
const {
  activeEditor,
  currentPageType,
  activeCategory,
  activePropertyTab,
  previewVisible,
  importVisible,
  importFile,
  uploadRef,
  dragIndex,
  dropPosition,
  offsetY,
  componentRefs,
  componentLabels,
  pageContentRef,
  syncScrollRef,
  lastScrollTop,
  previewAreaRef,
  previewContainerRef,
  phoneContainerRef,
  componentLabelStyle,
  activeComponent,
  isTempLabelShow,
  tempLabelStyle,
  tempLabelTargetIndex,
  tempLabelComponentName,
  isDragSortMode,

  // 计算属性
  nonTabBarComponents,
  tabBarComponents,
  componentLabelPositions,
  selectedDeleteBtnPosition,
  categorizedComponents,

  // 方法
  getComponentType,
  getPropertyPanelType,
  getIconComponent,
  getCategoryName,
  getComponentLabelStyle,
  updateComponentLabelPosition,
  showTempLabel,
  handlePageScroll,
  handleAddComponent,
  handleSelectComponent,
  handleUpdatePageConfig,
  handleUpdateComponentData,
  handleUpdateComponentStyles,
  handleUndo,
  handleRedo,
  handlePreview,
  handleSave,
  handleClear,
  handleImport,
  handleExport,
  handleFileChange,
  confirmImport,
  handleDragStart,
  handleDragOver,
  handleDrop,
  handleDragEnd,
  handleDeleteComponent,
  handleMoveUpLayer,
  handleMoveDownLayer,
  isSingletonComponent,
  hasSingletonComponent,
  handlePrevious,
  toggleDragSortMode,
  handleComponentDragStart,
  handleComponentDragOver,
  handleComponentDrop,
  handleResize,
  handleWheel,
  handlePageTypeChange,
  exportDesign,
  importDesign,
  // 工具函数
  getOriginalIndex,
  getTabBarOriginalIndex
} = useDesignTempLogic()
</script>

<style lang="scss" scoped>
.txz-editor {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 125px);
  background-color: #f5f5f5;
}

.editor-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.editor-content {
  flex: 1;
  height: calc(100% - 60px);
  overflow: hidden;
  display: flex; /* 添加flex布局 */
}

.component-list {
  width: 260px;
  background-color: #f8f9fa;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto;
  padding: 10px;
}

.component-category {
  margin-bottom: 15px;
}

.category-divider {
  position: relative;
  text-align: center;
  margin: 15px 0;

  span {
    background-color: #f8f9fa;
    padding: 0 10px;
    font-size: 14px;
    font-weight: 500;
    color: #606266;
    position: relative;
    z-index: 1;
  }
}

.component-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.component-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
    transform: translateY(-2px);
  }
}

.component-icon {
  margin-bottom: 5px;
}

.component-name {
  font-size: 12px;
  color: #303133;
}

.preview-area {
  flex: 1;
  background-color: #f5f5f5;
  position: relative;
  overflow: hidden;
}

.preview-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.sync-scroll-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.phone-and-labels {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.phone-container {
  width: 375px;
  min-height: 667px;
  background-color: #f5f5f5;
  border-radius: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  position: relative;
  display: flex;
  flex-direction: column;
  transition: border 0.3s ease;
}

/* 首页设计器边框样式 */
.phone-container.home-design {
  border: 3px solid #409eff;
}

/* 用户中心设计器边框样式 */
.phone-container.user-design {
  border: 3px solid #67c23a;
}

.phone-header {
  height: 30px;
  background-color: #000;
  position: relative;
  border-radius: 30px 30px 0 0;
}

.phone-notch {
  width: 150px;
  height: 25px;
  background-color: #000;
  border-radius: 0 0 15px 15px;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
}

.phone-screen {
  flex: 1;
  background-color: #fff;
  position: relative;
  overflow: hidden;
}

.page-content {
  flex: 1;
  min-height: calc(100% - 54px);
  overflow: visible;
  scrollbar-width: none;
  touch-action: none;
}

.component-wrapper {
  position: relative;
  margin: 8px 0;
  padding: 8px;
  border: 1px dashed transparent;
  border-radius: 4px;
  transition: all 0.2s;
  cursor: pointer;

  &:hover {
    border-color: rgba(64, 158, 255, 0.3);
  }
}

.component-selected {
  border-color: #409eff;
  border-style: solid;
}

.tabbar-container {
  width: 100%;
  height: 54px;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  position: absolute;
  bottom: 0;
  left: 0;
}

.phone-footer {
  height: 30px;
  background-color: #000;
  border-radius: 0 0 30px 30px;
}

.component-labels {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 5;
}

.deles {
  position: absolute;
  width: 120px;
  height: 28px;
  line-height: 28px;
  background: #f5f3d4;
  color: rgb(0, 0, 0);
  font-size: 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  cursor: pointer;
  transition: all 0.1s ease;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  &:hover {
    background-color: #ffc916;
    transform: translateY(-2px);
  }
}

.triangle-left {
  width: 0;
  height: 0;
  border-top: 6px solid transparent;
  border-bottom: 6px solid #f5f3d4;
  border-right: 6px solid transparent;
  margin-right: 8px;
}

.label-text {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}

.delete-icon {
  margin-left: 5px;
  cursor: pointer;

  &:hover {
    color: #f56c6c;
  }
}

.move-up-btn, .move-down-btn {
  width: 16px;
  height: 16px;
  background-color: rgba(64, 158, 255, 0.65);
  border-radius: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 5px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background-color: rgba(64, 158, 255, 0.85);
  }
}

.move-up-btn {
  clip-path: polygon(50% 0%, 100% 50%, 50% 100%);
}

.move-down-btn {
  clip-path: polygon(50% 100%, 100% 0%, 50% 0%);
}

.selected-delete-btn {
  position: absolute;
  width: 24px;
  height: 24px;
  background-color: rgba(245, 108, 108, 0.85);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.2s;
  border: 1px solid rgba(255, 255, 255, 0.5);

  &:hover {
    background-color: rgba(245, 108, 108, 0.95);
    transform: scale(1.1);
  }
}

.property-panel {
  width: 300px;
  background-color: #fff;
  border-left: 1px solid #e4e7ed;
  overflow-y: auto;
}

.component-info {
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }
}

.no-property-panel {
  padding: 20px;
  text-align: center;
}
</style>